package com.gitpull.controller;

import com.alibaba.excel.EasyExcel;
import com.gitpull.pojo.student;
import com.gitpull.service.excelService;
import com.gitpull.utils.Result;
import com.gitpull.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * EasyExcel导入导出
 * 负责处理上传和导入学生数据的请求
 * 自动创建MySQL数据表，如果已有表，先删除
 * Author: yun
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private excelService excelService;

    private static final Logger LOGGER = Logger.getLogger(ExcelController.class.getName());

    @PostMapping("/student")
    public Result<List<student>> importUserExcel(@RequestParam("file") MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            List<student> userList = EasyExcel.read(inputStream)
                    .head(student.class)
                    .sheet()
                    .doReadSync();
            excelService.saveExcel(userList);
            return ResultUtil.success(userList);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "导入Excel文件失败", e);
            return ResultUtil.fail("导入Excel文件失败");
        }
    }
}
